<template>
  <div class="market-plan-view view-container">

    <div class="main-content">
      <div class="list-container">

        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="区域招商" name="signedList" v-if="checkTabs('areaCode')"/>
          <el-tab-pane label="精细招商" name="fineList" v-if="checkTabs('fineCode')"/>
          <el-tab-pane label="终端直销" name="directList" v-if="checkTabs('directCode')"/>
          <el-tab-pane label="商业营销" name="businessList" v-if="checkTabs('business')"/>
        </el-tabs>

<!--        <component ref="refCom" :is="activeName" @on-allocation="onAllocation" @on-reject="onReject"/>-->

        <div class="filter-container">

          <el-form
                  :inline="true"
                  :model="formData"
                  label-position="right"
                  size="small"
                  class="filter-form-inline"
          >
            <el-row :gutter="20" style="margin-left: 0px; margin-right: 0px">
              <el-col :span="6">
                <el-form-item label="状态" style="width: 100%">
                  <el-select
                          v-model="formData.status"
                          clearable
                          style="width: 100%"
                          placeholder="请选择状态"
                          @change="listSearch"
                  >
                    <el-option
                            v-for="item in statusOption"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6" v-if="activeName != 'businessList'">
                <el-form-item label="规划地区" style="width: 100%" >
                  <el-cascader
                          :show-all-levels="false"
                          v-model="formData.area"
                          style="width: 100%;"
                          :options="citys"
                          placeholder="请选择适用地区"
                          :props="{ checkStrictly : true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
                          @change="listSearch"
                  />
                </el-form-item>

              </el-col>

              <el-col :span="6">
                <el-form-item label="跟进职员" style="width: 100%">
                  <el-select
                          v-model="formData.headId"
                          clearable
                          style="width: 100%"
                          placeholder="请选择职员"
                          @change="listSearch"
                  >
                    <el-option
                            v-for="item in headOptions"
                            :key="item.id"
                            :label="item.realName"
                            :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item style="width: 100%">
                  <el-button
                          class="border-btn"
                          @click="reset"
                  >重置</el-button>
                  <el-button
                          type="primary"
                          class="main-btn"
                          @click="listSearch"
                  >搜索</el-button>
                </el-form-item>
              </el-col>

            </el-row>
          </el-form>

        </div>

        <table-view v-show="activeName == 'signedList'" :data="tableData" @row-click="rowClick">
          <el-table-column
                  show-overflow-tooltip
                  align="left"
                  header-align="center"
                  prop="planInfo.productPopularName"
                  label="通用名"
                  :min-width="150"
          />
          <el-table-column
                  show-overflow-tooltip
                  align="center"
                  header-align="center"
                  prop="planInfo.productName"
                  label="商品名"
                  :min-width="100"
          />
          <el-table-column show-overflow-tooltip align="center" header-align="center" prop="planInfo.packSpecs" label="包装规格" :min-width="100"/>
          <el-table-column show-overflow-tooltip align="center" header-align="center" prop="planInfo.producer" label="生产厂家" :min-width="100"/>
          <el-table-column
                  align="center"
                  header-align="center"
                  label="规划招商地区"
                  :min-width="150"
          >
            <template #default="{row}">
              {{row.planDetail?.areaName ? row.planDetail?.cityName + "/" + row.planDetail?.areaName : row.planDetail?.cityName ? row.planDetail?.cityName : row.planDetail?.provinceName}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  header-align="center"
                  label="代理周期"
                  :min-width="100"
          >
            <template #default="scope">
              {{scope.row.planDetail?.agentCycle}}年
            </template>
          </el-table-column>
          <el-table-column
                  show-overflow-tooltip
                  align="center"
                  header-align="center"
                  label="最低销量"
                  :min-width="100"
          >
            <template #default="scope">
              <span v-if="scope.row.planDetail?.isIncrease == 1">{{scope.row.planDetail?.minSale}}{{getLabel('sell_unit',scope.row.planDetail?.sellUnit)}}/年</span>
              <span v-else>首年{{scope.row.planDetail?.minSale}}{{getLabel('sell_unit',scope.row.planDetail?.sellUnit)}},每年递增{{scope.row.planDetail?.increaseNum}}%</span>
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  header-align="center"
                  label="销量保证金(元)"
                  :min-width="150"
          >
            <template #default="scope">
              {{scope.row.planDetail?.sellEarnestMoney}}
            </template>
          </el-table-column>
          <el-table-column align="left" header-align="center" label="其他说明" prop="planDetail.remark" :min-width="150" show-overflow-tooltip/>
          <el-table-column header-align="center" align="center" label="跟进职员" prop="allocationAgent.headName"/>
          <el-table-column
                  header-align="center"
                  align="center"
                  label="开发跟进期限"
                  :min-width="140"
          >
            <template #default="scope">
              {{scope.row.date}}
              <!--        {{dateFormat('yyyy-mm-dd',scope.row.planInfo?.expireTime)}}-->
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  header-align="center"
                  label="状态"
                  fixed="right"
                  :min-width="150"
          >
            <template #default="scope">
              {{getStatus(scope.row)}}
              <!--        {{getLabel('signed_plan_detail_status',scope.row.planDetail?.detailStatus)}}-->
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  header-align="center"
                  label="操作"
                  fixed="right"
                  :min-width="200"
          >
            <template #default="{row}">
              <el-button
                      type="text"
                      @click="onEditorial(row)"
              >推荐代理</el-button>
              <el-button
                      v-if="row.planDetail?.detailStatus == -2 && userInfo.ID == row.allocationAgent?.headId"
                      type="text"
                      @click="onAccepted(row)"
              >接受</el-button>
              <el-button
                      v-if="row.planDetail?.detailStatus == -2 && userInfo.ID == row.allocationAgent?.headId"
                      type="text"
                      @click="onReject(row)"
              >拒绝</el-button>
              <el-button
                      v-auth="{v:['crm:marketing:planSigned:allocation'],bool:row.planDetail?.detailStatus == 0 || row.planDetail?.detailStatus == -3 || row.planDetail?.detailStatus == -4}"
                      type="text"
                      @click="onAllocation(row)"
              >分配</el-button>
            </template>
          </el-table-column>
        </table-view>

        <table-view v-show="activeName == 'fineList'" :data="tableData" @row-click="rowClick">
          <el-table-column
                  fixed="left"
                  show-overflow-tooltip
                  align="left"
                  header-align="center"
                  prop="planDetail.terminalName"
                  label="终端名称"
                  :min-width="150"
          />
          <el-table-column
                  fixed="left"
                  show-overflow-tooltip
                  align="center"
                  header-align="center"
                  prop="agentName"
                  label="所在地区"
                  :min-width="100"
          >
            <template #default="scope">
              {{scope.row.planDetail?.terProvinceName}}/{{scope.row.planDetail?.terCityName}}/{{scope.row.planDetail?.terAreaName}}
            </template>
          </el-table-column>
          <el-table-column
                  fixed="left"
                  show-overflow-tooltip
                  align="center"
                  header-align="center"
                  prop="planInfo.productPopularName"
                  label="通用名"
                  :min-width="100"
          />
          <el-table-column
                  show-overflow-tooltip
                  align="center"
                  header-align="center"
                  prop="planInfo.productName"
                  label="商品名"
                  :min-width="100"
          />
          <el-table-column
                  show-overflow-tooltip
                  align="center"
                  header-align="center"
                  prop="planInfo.packSpecs"
                  label="包装规格"
                  :min-width="100"
          >
          </el-table-column>
          <el-table-column show-overflow-tooltip align="center" header-align="center" prop="planInfo.producer" label="生产厂家" :min-width="100"/>
          <el-table-column
                  header-align="center"
                  align="center"
                  label="准入模式"
                  :min-width="100">
            <template #default="scope">
              {{getLabel('access_mode',scope.row.planInfo.accessMode)}}
            </template>
          </el-table-column>
          <el-table-column
                  header-align="center"
                  align="center"
                  prop="planInfo.terminalPrice"
                  label="终端价(元)"
                  :min-width="100"
          />
          <el-table-column
                  header-align="center"
                  align="center"
                  label="营销体量"
                  :min-width="100"
          >
            <template #default="scope">
              {{ getLabel('sales_volume',scope.row.planDetail.salesVolume) }}
            </template>
          </el-table-column>
          <el-table-column
                  header-align="center"
                  align="center"
                  label="终端开发期限"
                  :min-width="140"
          >
            <template #default="scope">
              {{dateFormat('yyyy-mm-dd',scope.row.planDetail.expireTime)}}
            </template>
          </el-table-column>
          <el-table-column header-align="center" align="center" prop="address" label="开发保证金(元)" width="150px">
            <template #default="scope">
              <span v-if="scope.row.planDetail?.devEarnestMoney">{{scope.row.planDetail?.devEarnestMoney}}</span>
              <span v-else>未设置</span>
            </template>
          </el-table-column>
          <el-table-column header-align="center" align="center" label="跟进职员" prop="allocationAgent.headName"/>
          <el-table-column
                  header-align="center"
                  align="center"
                  label="开发跟进期限"
                  :min-width="140"
          >
            <template #default="scope">
              {{scope.row.date}}
              <!--        {{dateFormat('yyyy-mm-dd',scope.row.planInfo.expireTime)}}-->
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  header-align="center"
                  label="状态"
                  fixed="right"
                  :min-width="150"
          >
            <template #default="scope">
              {{getStatus(scope.row)}}
              <!--        {{getLabel('fine_plan_detail_status',scope.row.planDetail?.detailStatus)}}-->
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  header-align="center"
                  label="操作"
                  fixed="right"
                  :min-width="200"
          >
            <template #default="{row}">
              <el-button
                      type="text"
                      @click="onEditorial(row)"
              >推荐代理</el-button>
              <el-button
                      v-if="row.planDetail?.detailStatus == -2 && userInfo.ID == row.allocationAgent?.headId"
                      type="text"
                      @click="onAccepted(row)"
              >接受</el-button>
              <el-button
                      v-if="row.planDetail?.detailStatus == -2 && userInfo.ID == row.allocationAgent?.headId"
                      type="text"
                      @click="onReject(row)"
              >拒绝</el-button>
              <el-button
                      v-auth="{v:['crm:marketing:planFine:allocation'],bool:row.planDetail.detailStatus == 0 || row.planDetail?.detailStatus == -3 || row.planDetail?.detailStatus == -4 || row.planDetail?.detailStatus == -5}"
                      type="text"
                      @click="onAllocation(row)"
              >分配</el-button>
            </template>
          </el-table-column>
        </table-view>

        <table-view v-show="activeName == 'directList'" :data="tableData" @row-click="rowClick">
          <el-table-column
                  :min-width="150"
                  align="center"
                  fixed="left"
                  header-align="center"
                  label="通用名"
                  prop="planInfo.productPopularName"
                  show-overflow-tooltip
          />
          <el-table-column
                  :min-width="100"
                  align="center"
                  header-align="center"
                  label="商品名"
                  prop="planInfo.productName"
                  show-overflow-tooltip
          />
          <el-table-column
                  :min-width="100"
                  align="center"
                  header-align="center"
                  label="包装规格"
                  prop="planInfo.packSpecs"
                  show-overflow-tooltip
          />
          <el-table-column :min-width="100" align="center" header-align="center" label="生产厂家" prop="planInfo.producer"
                           show-overflow-tooltip/>
          <el-table-column
                  :min-width="100"
                  align="center"
                  header-align="center"
                  label="产品属性"
                  show-overflow-tooltip
          >
            <template #default="scope">
              <span> {{ getLabel('product_attribute', scope.row.planDetail?.productAttribute) }}</span>
            </template>
          </el-table-column>
          <el-table-column
                  :min-width="100"
                  align="center"
                  header-align="center"
                  label="终端价(元)"
                  prop="planInfo.terminalPrice"
          />
          <el-table-column
                  :min-width="150"
                  align="center"
                  header-align="center"
                  label="直销地区"
                  show-overflow-tooltip
          >
            <template #default="scope">
              {{ scope.row.planDetail?.provinceName }}/{{
              scope.row.planDetail?.cityName
              }}/{{ scope.row.planDetail?.areaName }}/{{scope.row.planDetail?.streetName}}
            </template>
          </el-table-column>
          <el-table-column
                  :min-width="150"
                  align="center"
                  header-align="center"
                  label="规划开发终端数量"
          >
            <template #default="scope">
              {{ scope.row.planDetail.devTerminalNum }} 家
            </template>
          </el-table-column>
          <el-table-column align="center" header-align="center" label="跟进职员" prop="allocationAgent?.headName">
            <template #default="scope">
              {{ scope.row.allocationAgent?.headName }}
            </template>
          </el-table-column>
          <el-table-column
                  header-align="center"
                  align="center"
                  label="开发跟进期限"
                  :min-width="140"
          >
            <template #default="scope">
              <span>{{scope.row.date}}</span>
            </template>
          </el-table-column>
          <el-table-column
                  :min-width="150"
                  align="center"
                  fixed="right"
                  header-align="center"
                  label="状态"
          >
            <template #default="scope">
              {{ getStatus(scope.row) }}
              <!--        {{ getLabel('fine_plan_detail_status',scope.row.planDetail?.detailStatus) }}-->
            </template>
          </el-table-column>
          <el-table-column
                  :min-width="150"
                  align="center"
                  fixed="right"
                  header-align="center"
                  label="操作"
          >
            <template #default="{row}">
              <el-button
                      v-if="row.planDetail?.detailStatus == -2 && userInfo.ID == row.allocationAgent?.headId"
                      type="text"
                      @click="onAccepted(row)"
              >接受</el-button>
              <el-button
                      v-if="row.planDetail?.detailStatus == -2 && userInfo.ID == row.allocationAgent?.headId"
                      type="text"
                      @click="onReject(row)"
              >拒绝</el-button>
              <el-button
                      v-auth="{v:['crm:marketing:planDirect:allocation'],bool:row.planDetail.detailStatus == 0 || row.planDetail?.detailStatus == -3 || row.planDetail?.detailStatus == -4 || row.planDetail?.detailStatus == -5}"
                      type="text"
                      @click="onAllocation1(row)"
              >分配</el-button>
            </template>
          </el-table-column>
        </table-view>

        <table-view v-show="activeName == 'businessList'" :data="tableData" @row-click="rowClick">
          <el-table-column
                  :min-width="150"
                  align="center"
                  fixed="left"
                  header-align="center"
                  label="规划编号"
                  prop="planInfo.planNo"
                  show-overflow-tooltip
          />
          <el-table-column
                  :min-width="150"
                  align="center"
                  fixed="left"
                  header-align="center"
                  label="规划名称"
                  prop="planInfo.planName"
                  show-overflow-tooltip
          />
          <el-table-column
                  :min-width="150"
                  align="center"
                  fixed="left"
                  header-align="center"
                  label="通用名"
                  prop="planInfo.productPopularName"
                  show-overflow-tooltip
          />
          <el-table-column
                  :min-width="100"
                  align="center"
                  header-align="center"
                  label="商品名"
                  prop="planInfo.productName"
                  show-overflow-tooltip
          />
          <el-table-column
                  :min-width="100"
                  align="center"
                  header-align="center"
                  label="包装规格"
                  prop="planInfo.packSpecs"
                  show-overflow-tooltip
          />
          <el-table-column :min-width="100" align="center" header-align="center" label="生产厂家" prop="planInfo.producer"
                           show-overflow-tooltip/>
          <el-table-column align="center" header-align="center" label="跟进职员">
            <template #default="scope">
              {{scope.row.allocationAgent?.headName}}
            </template>
          </el-table-column>
          <el-table-column
                  header-align="center"
                  align="center"
                  label="开发跟进期限"
                  :min-width="140"
          >
            <template #default="scope">
              {{scope.row.date}}
            </template>
          </el-table-column>
          <el-table-column
                  :min-width="150"
                  align="center"
                  fixed="right"
                  header-align="center"
                  label="状态"
          >
            <template #default="scope">
              {{ getStatus(scope.row) }}
              <!--        {{ getLabel('fine_plan_detail_status',scope.row.planDetail?.detailStatus) }}-->
            </template>
          </el-table-column>
          <el-table-column
                  :min-width="150"
                  align="center"
                  fixed="right"
                  header-align="center"
                  label="操作"
          >
            <template #default="{row}">
              <el-button
                      v-if="row.planDetail?.detailStatus == -2 && userInfo.ID == row.allocationAgent?.headId"
                      type="text"
                      @click="onAccepted(row)"
              >接受</el-button>
              <el-button
                      v-if="row.planDetail?.detailStatus == -2 && userInfo.ID == row.allocationAgent?.headId"
                      type="text"
                      @click="onReject(row)"
              >拒绝</el-button>
              <el-button
                      v-auth="{v:['crm:marketing:planBusiness:allocation'],bool:row.planDetail.detailStatus == 0 || row.planDetail?.detailStatus == -3 || row.planDetail?.detailStatus == -4 || row.planDetail?.detailStatus == -5}"
                      type="text"
                      @click="onAllocation2(row)"
              >分配</el-button>
            </template>
          </el-table-column>
        </table-view>

        <Pagination
                v-model:page="formData.page"
                v-model:limit="formData.pageSize"
                style="display: flex; justify-content: flex-end"
                :total="total"
                @pagination="getList"
        />

      </div>
    </div>

    <allocationDialog ref="allocationDialog" @success="success"></allocationDialog>

    <rejectDialog ref="rejectDialog" @success="success"/>

    <altDirectDialog ref="altDirectDialog" @success="success"/>

    <altBusinessDialog ref="altBusinessDialog" @success="success"/>
  </div>
</template>

<script>
import {dateFormat} from "../../../../../../utils/date";
import {crmStore} from "../../../../store";
import area from "../../../../../../utils/area";
import {useRouter} from 'vue-router'
import {defineComponent, defineAsyncComponent, getCurrentInstance, inject, onMounted, reactive, ref, toRefs, onActivated} from 'vue'

export default defineComponent({
  name: 'marketingPlanList',
  components: {
    allocationDialog : defineAsyncComponent(
            () => import('./modules/allocationDialog.vue')
    ),
    rejectDialog : defineAsyncComponent(
            () => import('./modules/rejectDialog.vue')
    ),
    altDirectDialog : defineAsyncComponent(
            () => import('./modules/altDirectDialog.vue')
    ),
    altBusinessDialog : defineAsyncComponent(
            () => import('./modules/altBusinessDialog.vue')
    )
  },
  setup() {
    const router = useRouter()
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    const citys = area
    const userInfo = crmStore.getters['user/userInfo']
    const statusOption = ref([
      {
        label:'待分配',
        value:'1'
      },
      {
        label:'分配待确认',
        value:'2'
      },
      {
        label:'已拒绝',
        value:'3'
      },
      {
        label:'已分配',
        value:'4'
      },
      {
        label:'代理开发失败',
        value:'-4'
      }
    ])
    var data = reactive({
      activeName: 'signedList',
      tableData:[],
      formData:{
        listType:'1',
        page:1,
        pageSize:20,
        status:'',
        area:[],
      },
      total:0,
      headOptions:crmStore.getters['company/getHeadOptions'],
      allocationDialog:null,
      rejectDialog:null,
      refCom:null,
      altDirectDialog:null,
      altBusinessDialog:null,
    })

    onMounted(() => {
      getList()
    })

    onActivated(() =>{
      getList()
    })

    const listSearch = () => {
      data.formData.page = 1
      getList()
    }

    const reset = () => {
      data.formData = {
        listType:'1',
        page:1,
        pageSize:20,
        status:'',
        area:[],
      }
      getList()
    }

    const handleClick = () => {
      data.tableData = []
      if (data.activeName == 'businessList'){
        data.formData.area = []
      }
      listSearch()
    }

    const getList = () => {
      let a = {...data.formData}
      a.planType = '1'
      if (data.activeName == 'signedList'){
        a.planType = '2'
      }else if (data.activeName == 'directList'){
        a.planType = '3'
      }else if (data.activeName == 'businessList'){
        a.planType = '4'
      }
      if (a.area.length){
        if (a.area.length == 1){
          a.provinceCode = a.area[0]
        }else if (a.area.length == 2){
          a.cityCode = a.area[1]
        }else if (a.area.length == 3){
          a.areaCode = a.area[2]
        }
      }
      api.plan.PLAN_DETAIL_LIST(a).then(res=>{
        if (!res.code){
          data.total = res.data.total
          data.tableData = res.data.list || [];
          data.tableData.forEach(a=>{
            let str = getDate(a)
            a.date = str
          })
        }else {
          currentInstance.proxy.customMessage({type:'error',message:res.msg})
        }
      })
    }

    const rowClick = (row,column) => {
      if (column.label === '操作') return
      if (data.activeName == 'signedList'){
        router.push({name:'marketPlanDetail',query:{id:row.planDetail.id}})
      }else if (data.activeName == 'fineList'){
        router.push({name:'marketPlanDetail1',query:{id:row.planDetail.id}})
      }else if (data.activeName == 'directList'){
        router.push({name:'marketPlanDetail2',query:{id:row.planDetail.id}})
      }else if (data.activeName == 'businessList'){
        router.push({name:'marketPlanDetail3',query:{id:row.planDetail.id}})
      }

    }

    const getDate = (row) => {

      if (row.allocationAgent && row.allocationAgent.allocationAgentDetails){
        let str = ''
        row.allocationAgent.allocationAgentDetails.forEach(item=>{
          if (!str){
            str = item.dealTime
          }else if (new Date(str).getTime() < new Date(item.dealTime)) {
            str = item.dealTime
          }
        })
        return dateFormat('yyyy-mm-dd',str)
      }else {
        return ''
      }

    }

    const getStatus = (row) => {
      let str = ''

      switch (row.planDetail?.detailStatus) {
        case "0":
          str = '待分配';
          break;
        case "-2":
          str = '分配待确认';
          break;
        case "-3":
          str = '已拒绝';
          break;
        case "-4":
          str = '代理开发失败';
          break;
        case "-5":
          str = '终端开发失败';
          break;
        case "1":
          str = '已分配';
          break;
        case "2":
          str = '已分配';
          break;
        case "3":
          str = '已分配';
          break;
      }

      return str
    }

    const checkTabs = (type) => {
      return crmStore.getters['company/getMenuPermission'](type)
    }

    const onEditorial = (row) => {
      router.push({path:'/editorial/agent/create',query:{id:row.planDetail.id}})
    }

    const success = () => {
      // data.refCom.getList()
      getList()
    }

    const onAllocation = (row) => {
      data.allocationDialog.open(row)
    }

    const onAllocation1 = (row) => {
      data.altDirectDialog.open(row)
    }

    const onAllocation2 = (row) => {
      data.altBusinessDialog.open(row)
    }

    const onReject = (row) => {
      data.rejectDialog.open(row.planDetail.id)
    }

    const onAccepted = (row) => {
      currentInstance.proxy
              .alertBox({
                message: '确认同意接受此任务？',
                title: '接受',
              })
              .then(() => {
                api.plan.ALLOCATION_AGENT_DEAL({planDetailId:row.planDetail.id,type:'1'}).then(res=>{
                  if (!res.code){
                    currentInstance.proxy.customMessage({type:'success',message:'处理成功'})
                    getList()
                  }else {
                    currentInstance.proxy.customMessage({type:'error',message:res.msg})
                  }
                })
              })
              .catch((err) => {
                console.log(err)
              })
    }

    return {
      ...toRefs(data),
      citys,
      userInfo,
      statusOption,

      success,
      onAllocation,
      onAllocation1,
      onAllocation2,
      onReject,
      listSearch,
      getList,
      rowClick,
      getDate,
      getStatus,
      onEditorial,
      onAccepted,
      handleClick,
      reset,
      checkTabs,
    }
  }
})
</script>

<style scoped>

</style>
